package com.project.class4_8.proxy.util;

import com.project.class4_8.proxy.dao.IRoomDao;
import com.project.class4_8.proxy.dao.IUserDao;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class DaoFactory {
    private static Map<Class,Object> map =new HashMap<>();
    private static final String dirPath="D:\\JAVA\\程序\\javaSE\\src\\com\\project\\class4_8\\proxy\\dao\\impl";
    static {
        File file =new File(dirPath);
        File [] array=file.listFiles();

        for(File f: array){
            if (f.isFile()&& f.getName().endsWith(".java")){
                String path ="com.project.class4_8.proxy.dao.impl."+
                        f.getName().substring(0,f.getName().indexOf(".java"));
                try {
                    //加载类得到类模板
                    Class c=Class.forName(path);

                    Class obj= c.getInterfaces()[0];//得到该类的实现接口
                    Object classObj= c.getConstructor().newInstance();
                    map.put(obj,classObj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static Object getObject(Class classObj){
        return map.get(classObj);
    }
    public static void main(String[] args) {
        Object one =DaoFactory.getObject(IUserDao.class);
        Object two =DaoFactory.getObject(IRoomDao.class);
        System.out.println(one+"   "+two);
    }
}
